<?php


namespace app\article\controller;


use app\article\model\ArticleClassifyModel;
use app\article\model\ArticleConfigModel;
use app\article\model\ArticleDateModel;
use app\article\model\ArticleModel;
use app\article\model\ArticleRecordModel;
use app\BaseController;
use app\card\model\CardCount;
use app\card\model\CardJob;
use app\card\model\User;
use app\card\model\UserInfo;
use app\Common\model\LongbingCardCollection as CollectionModel;
use app\dynamic\model\CardCompany;
use app\radar\model\RadarCount;
use think\facade\Db;
use think\facade\View;
use think\Response;
use think\response\Json;

class ArticleHtml extends BaseController
{
    public function msg()
    {
        if (!isset($_GET['echostr']))
        { //接收消息和事件，并发送消息
            $postStr = file_get_contents("php://input");
            if ($postStr)
            {
                $this->sendMsg($postStr, $_GET['i']);
            } else {
                echo "success";
                exit;
            }
            echo "success";
            exit;
        } else { //验证消息的确来自微信服务器
            $configModel = new ArticleConfigModel();
            $config = $configModel->where(['uniacid' => $_GET['i']])->find();
            if (!$config || !$config['mini_token']) {
                echo '请联系管理员检查文章配置.';
                exit;
            }
            $echoStr = $_GET["echostr"];
            if ($this->checkSignature($config['mini_token']))
            {
                header('content-type:text');
                echo $echoStr;
                exit;
            } else {
                echo $echoStr . '+++' . $config['mini_token'] . time();
                exit;
            }
        }
    }


    private function checkSignature($token)
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature)
        {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @Purpose: 发送指定内容给客户
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    protected function sendMsg($postStr, $uniacid)
    {
        global $_W;
        $postStr = json_decode($postStr, true);
        $RX_TYPE = $postStr['MsgType'];
        $target = $postStr['FromUserName'];
        $ThumbUrl = isset($postStr['ThumbUrl']) ? $postStr['ThumbUrl'] : '';
        $ToUserName = $postStr['ToUserName'];

        //消息类型分离
        switch ($RX_TYPE) {
            //  发送小程序事件
            case "miniprogrampage":   //事件
                $url = $postStr['PagePath'];
                $urlArr = explode('?', $url);
                $par = $urlArr[1];
                $par = explode('&', $par);
                $par_id = $par[0];
                $user = $par[1];

                $par_id = explode('=', $par_id);
                $par_id = $par_id[1];
                $user = explode('=', $user);
                $user = $user[1];
                $res = $this->sendToUser($par_id, $target, $user, $ThumbUrl, $uniacid);
                $arr = json_decode($res, true);
                if (isset($arr['errcode']) && $arr['errcode'] == 40001)
                {
                    $config    = longbingGetAppConfig($uniacid);
                    $appid     = $config[ 'appid' ];
                    $appidMd5 = md5($appid);
                    if (is_file(IA_ROOT . '/data/tpl/web/' . $appidMd5 . '.txt'))
                    {
                        unlink(IA_ROOT . '/data/tpl/web/' . $appidMd5 . '.txt');
                    }
                    $res = $this->sendToUser($par_id, $target, $user, $ThumbUrl, $uniacid);
                }
                return $res;
                break;
            default:
                $res = $this->sendDefault($target, $ToUserName, $uniacid);
                $arr = json_decode($res, true);
                if (isset($arr['errcode']) && $arr['errcode'] == 40001)
                {
                    $config    = longbingGetAppConfig($uniacid);
                    $appid     = $config[ 'appid' ];
                    $appidMd5 = md5($appid);

                    if (is_file(IA_ROOT . '/data/tpl/web/' . $appidMd5 . '.txt'))
                    {
                        unlink(IA_ROOT . '/data/tpl/web/' . $appidMd5 . '.txt');
                    }
                    $res = $this->sendDefault($target, $ToUserName, $uniacid);
                }
                return $res;
        }
        return true;
    }


    /**
     * @Purpose: 发送客服消息
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    protected function sendToUser($id, $target, $user, $ThumbUrl, $uniacid)
    {
        $ac = $this->getAccessToken($uniacid);

        $configModel = new ArticleConfigModel();
        $config = $configModel->where(['uniacid' => $uniacid])->find();
        if (!$config || !$config['gzh_appid'])
        {
            echo '请联系管理员检查文章配置!!';
            die;
        }
        $model_name = config('app.AdminModelList')['app_model_name'];

        $articleModel = new ArticleModel();
        $articleModel->where(['id' => $id])->update(['status' => 1]);
        $articleModel->where(['id' => $id])->inc('share_self');
        $postUrl = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $ac;
        if(defined('IS_WEIQIN'))
        {
            global $_W;
            $url = $_W['siteroot'] . "app/index.php?i=$uniacid&id=$id&uid=$user&t=0&v=2.0&from=wxapp&c=entry&a=wxapp&do=api&core=core2&m=$model_name&s=/article/articleHtml/html";
        } else {
            $url = $url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?s=/article/articleHtml/html&id=' . $id . '&uid=' . $user . '&i=' . $uniacid;
        }

        $url = urlencode($url);
        $articleUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$config['gzh_appid']}&redirect_uri={$url}&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect";

        $data = array(
            'touser' => $target,
            'msgtype' => 'link',
            "link" => [
                "title" => "点击进入, 即可分享到朋友圈",
                "description" => "打开页面, 点击右上角【...】分享到朋友圈",
                "url" => $articleUrl,
                "thumb_url" => $ThumbUrl
            ]
        );


        $data = json_encode($data, JSON_UNESCAPED_UNICODE);


        $res = longbingCurl($postUrl, $data, 'POST');
        return $res;
    }


    /**
     * @Purpose: 发送默认消息给客户
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    protected function sendDefault($target, $ToUserName, $uniacid)
    {

        $ac = $this->getAccessToken($uniacid);


        $postUrl = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $ac;

        $data = array(
            'touser' => $target,
            'msgtype' => 'text',
            'text' => ['content' => '点击发送“小程序”获取文章链接']
        );

        $data = json_encode($data, JSON_UNESCAPED_UNICODE);

        $res = longbingCurl($postUrl, $data, 'POST');
// file_put_contents('/home/wwwroot/testing.migugu.com/addons/longbing_card/core2/runtime/article/log/201911/14.log', json_encode($res, 256), FILE_APPEND);

        return $res;
    }

    private function getAccessToken($uniacid)
    {
        return longbingGetAccessToken ( $uniacid );

        // $access_token = getCache('access_token', $uniacid);
        //   file_put_contents('/home/wwwroot/testing.migugu.com/addons/longbing_card/core2/runtime/article/log/201911/14.log', json_encode($access_token, 256) . PHP_EOL, FILE_APPEND);
        // if ($access_token) {
        //     return $access_token;
        // }

        // $config    = longbingGetAppConfig($uniacid);
        // $appid     = $config[ 'appid' ];
        // $appsecret = $config[ 'app_secret' ];

        // $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
        // $data = file_get_contents($url);
        // $data = json_decode($data, true);
        //  file_put_contents('/home/wwwroot/testing.migugu.com/addons/longbing_card/core2/runtime/article/log/201911/14.log', json_encode($data, 256) . PHP_EOL, FILE_APPEND);
        // if (!isset($data['access_token'])) {
        //     return false;
        // }
        // $access_token = $data['access_token'];
        // setCache('access_token', $access_token,  60,  $uniacid);

        // return $access_token;

    }


    public function html()
    {

        global $_W;

        $uniacid = $_W['uniacid'] ?? $_GET['i'];

        if (!isset($_W['uid']))
        {
            $_W['uid'] = 0;
        }

        $user = '';

        $job = '';

        $code_icon = '';

        $configModel = new ArticleConfigModel();

        $config = $configModel->where(['uniacid' => $_GET['i']])->find();

        if (!$config || !$config['gzh_appid'] || !$config['gzh_secret'])
        {
            echo '请联系管理员检查文章配置!';
            die;
        }
        $appid = $config['gzh_appid'];

        $secret = $config['gzh_secret'];

        if (isset($_GET['code']))
        {

            $code = $_GET['code'];


            $code_icon = '&code='.$code;

            $cache = cache($code);

            $cache = [];

            if (!$cache)
            {


                $url     = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";

                $info    = file_get_contents($url);

                $infoArr = json_decode($info, true);

                if (isset($infoArr['errcode']))
                {

                    $url  = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];

                    $url  = str_replace($code_icon,'',$url);

                    $url  = str_replace('&from=singlemessage','',$url);

                    $url  = str_replace('&state=STATE','',$url);


                    $url2 = urlencode($url);

                    $articleUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$config['gzh_appid']}&redirect_uri={$url2}&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect";

                    header("Location:" . $articleUrl);

                    exit;
                }

                if (!isset($infoArr['errcode']))
                {

                    cache($code, $info, 300);

                }

            } else {

                $infoArr = json_decode($cache, true);

            }

            if (isset($infoArr['access_token']))
            {

                $user_url  = "https://api.weixin.qq.com/sns/userinfo?access_token={$infoArr['access_token']}&openid=OPENID&lang=zh_CN";
//                $token_arr = $infoArr;
                $user_info = file_get_contents($user_url);

                $infoArr   = json_decode($user_info, true);

                if (isset($infoArr['openid']))
                {
                    $userModel = new User();
                    $openid = $infoArr['openid'];
                    $unionid = isset($infoArr['unionid']) ? $infoArr['unionid'] : '';

                    if ($unionid)
                    {

                        $user = $userModel->where(['unionid' => $unionid, 'uniacid' => $uniacid])->find();

                        if (!$user)
                        {
                            $insertData = ['openid' => $openid];
                            $insertData['nickName'] = $infoArr['nickname'];
                            $insertData['avatarUrl'] = $infoArr['headimgurl'];
                            $insertData['scene'] = 0;
                            $insertData['pid'] = 0;
                            $insertData['uniacid'] = $_GET['i'];
                            $insertData['is_qr'] = 0;
                            $insertData['unionid'] = $unionid;
                            $insertData['openid'] = $infoArr['openid'];
                            $insertData['ip'] = '';
                            $insertData['target_id'] = $_GET['id'];
                            $insertData['is_article'] = 1;

                            $userModel->data($insertData);
                            $userModel->save();

                            $user = $userModel->where(['unionid' => $unionid])->find();
                        }
                    }
                    else {
                        $user = $userModel->where(['openid' => $openid, 'uniacid' => $uniacid])->find();
                        if (!$user) {
                            $insertData = ['openid' => $openid];
                            $insertData['nickName'] = $infoArr['nickname'];
                            $insertData['avatarUrl'] = $infoArr['headimgurl'];
                            $insertData['scene'] = 0;
                            $insertData['pid'] = 0;
                            $insertData['uniacid'] = $_GET['i'];
                            $insertData['is_qr'] = 0;
                            $insertData['unionid'] = $unionid;
                            $insertData['openid'] = $infoArr['openid'];
                            $insertData['ip'] = '';
                            $insertData['target_id'] = $_GET['id'];
                            $insertData['is_article'] = 1;

                            $userModel->data($insertData);
                            $userModel->save();

                            $user = $userModel->where(['openid' => $openid,  'uniacid' => $uniacid ])->find();
                        }
                    }
                } else {


                    $url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];

                    $url = str_replace($code_icon,'',$url);

                    $url  = str_replace('&from=singlemessage','',$url);

                    $url  = str_replace('&state=STATE','',$url);

                    $url2 = urlencode($url);

                    $articleUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$config['gzh_appid']}&redirect_uri={$url2}&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect";

                    header("Location: " . $articleUrl);
                    die;
                }
            }

        } else {
            $url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];

            $url = str_replace('&state=STATE','',$url);

            $url  = str_replace('&from=singlemessage','',$url);

            $url2 = urlencode($url);

            $articleUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$config['gzh_appid']}&redirect_uri={$url2}&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect";
            header("Location: " . $articleUrl);
            die;
        }




        if(!empty($user->id)&&!empty($_GET['uid'])){
            $collection_model = new CollectionModel();
            $data = $collection_model->getCollection(['uniacid' => $uniacid ,'uid' => $user->id ,'to_uid' => $_GET['uid']]);
            if(!empty($data)  )
            {
                if(empty($data['intention']))
                {
                    $collection_model = new CollectionModel();
                    $collection_model->updateCollection(['id' => $data['id']] ,['intention' => 1]);
                }
            }else{
                $data = ['uniacid' => $uniacid ,'uid' => $user->id ,'to_uid' => $_GET['uid'] , 'distribution' => 1 ,'intention' => 1];
                $collection_model = new CollectionModel();
                $collection_model->createCollection($data);
            }
        }




        $articleModel = new ArticleModel();

        $article = $articleModel->alias('a')
            ->field([
                'a.id', 'a.user_id', 'a.classify_id', 'a.title', 'a.cover', 'a.view', 'a.share', 'a.create_time',
                'b.content', 'a.content as a_content', 'a.status', 'a.uniacid'
            ])
            ->join('lb_marketing_article_content b', 'a.content = b.id', 'left')
            ->where(['a.id' => $_GET['id'], 'a.status' => 1])
            ->find();
        $userInfo = [];
        $company = [];
        $record_id = 0;
        $count_id = 0;


        if ($article)
        {
//            dump($user['id'],$article['user_id']);exit;

            if ($user && $user['id'] != $article['user_id'])
            {



                $time = time();
                $countModel = new CardCount();

                $son_time = $time - 4;

                $check_ex = $countModel->where([
                    ['create_time', '>', $son_time],
                    ['user_id' ,'=', $user->id],
                    ['to_uid' , '=',  $_GET['uid']],
                    ['target', '=',  $_GET['id']],
                    ['type', '=',  12]
                ])
                    ->find();

//                dump($check_ex,$_GET['id'],$_GET['uid'],$user->id);exit;
                if (!$check_ex)
                {

                    $article->view = $article->view + 1;
                    $article->save();
//                    $articleModel->where(['id' => $_GET['id']])->inc('view');

                    $countModel->user_id = $user->id;
                    $countModel->to_uid = $_GET['uid'];
                    $countModel->sign = 'view';
                    $countModel->type = 12;
                    $countModel->uniacid = $_GET['i'];
                    $countModel->target = $_GET['id'];
                    $countModel->save();
                    $count_id = $countModel->id;

//                    dump($count_id);exit;

                    $recordModel = new ArticleRecordModel();
                    $count = $recordModel
                        ->where([
                            'article_id' => $article['id'],
                            'user_id' => $user['id'],
                            'staff_id' => $article['user_id'],
                            'type' => 1,
                            'uniacid' => $article['uniacid'],
                        ])
                        ->count();

                    $recordModel->article_id = $article['id'];
                    $recordModel->user_id = $user['id'];
                    $recordModel->staff_id = $article['user_id'];
                    $recordModel->type = 1;
                    $recordModel->uniacid = $article['uniacid'];
                    $recordModel->number = $count + 1;
                    $recordModel->save();
                    $record_id = $recordModel->id;
                    if ($user && $user['id'] != $article['user_id'] && $article['user_id'] != 0) {
                        $this->setClients($article['user_id'], $user['id'], $article['id'], $recordModel->id, $article['uniacid']);
                    }


                    //发送雷达通知
                    if (!empty($countModel->id))
                    {
                        $push_data = array(
                            'action' => 'SendWxServiceNotice',
                            'event' => 'SendWxServiceNotice',
                            'count_id' => $countModel->id
                        );
                        publisher(json_encode($push_data, true), 5000);
                    }
                }


            }


            $tmp_time = $article['create_time'];
            $article['create_time2'] = lb_friendly_date($tmp_time);

            $userModel = new UserInfo();
            $userInfo = $userModel
                ->field('name, avatar, company_id,phone, job_id')
                ->where(['fans_id' => $_GET['uid']])
                ->find();
            $company_id = 0;
            if ($userInfo)
            {
//                $userInfo['avatar'] = $this->lb_src_trans($userInfo['avatar'], false, $_W);
                if ($userInfo['company_id'])
                {
                    $company_id = $userInfo['company_id'];
                }
            }
            $job = '';
            if (isset($userInfo['job_id']) && $userInfo['job_id'])
            {
                $jobModel = new CardJob();
                $job = $jobModel->where(['id' => $userInfo['job_id']])->find();
            }
            if (!$job)
            {
                $job = array('name' => '');
            }

            $companyModel = new CardCompany();
            $company = '';

            if ($company_id)
            {
                $company = $companyModel->where(['id' => $company_id])->find();
            }
            if (!$company || !$company_id)
            {
                $company = $companyModel->where(['uniacid' => $_GET['i'], 'status' => 1])->find();
            }
            if ($company)
            {
//                $company['logo'] = $this->lb_src_trans($company['logo'], false, $_W);
            }
        }

        $articles = $articleModel
            ->field('id, title, classify_id, cover, create_time')
            ->order(['top'=>'desc','view' => 'desc', 'update_time' => 'desc', 'id' => 'desc'])
            ->where([
                ['user_id', '=', $_GET['uid']],
                ['status', '=', 1],
                ['id', '<>', $_GET['id']],
            ])
            ->limit(5)
            ->select()->toArray();

        if ($articles)
        {

            foreach ($articles as $index => $item) {

                $item['time'] = $item['create_time'];
                $articles[$index]['create_time2'] = lb_friendly_date($item['time']);
            }
        }


        $card_code_data = ["data" => ["staff_id" => $_GET['uid'] ,"pid" => $_GET['uid'] ,"type" => 4 ,"key" => 1]];
        $qr_path_src = 'image/' . $uniacid . '/' . 'wxcode/' . md5($uniacid . json_encode($card_code_data ,true)) . 'jpeg';
        $qr_paths = ['src' => $qr_path_src];

        if(!longbingHasLocalFile($qr_path_src))
        {
            $wxcode_data = longbingCreateWxCode($uniacid ,$card_code_data);
            if(isset($wxcode_data['path']) && !empty($wxcode_data['path'])) $qr_paths['src'] = $wxcode_data['path'];
        }
        $qr_paths = transImagesOne($qr_paths ,['src']);
        $qr_path = $qr_paths['src'];

        $model_name = config('app.AdminModelList')['app_model_name'];

        if (defined('IS_WEIQIN') ) {
            $list_url = 'https://' . $_SERVER['HTTP_HOST'] . "/app/index.php?i={$_GET['i']}&uid={$_GET['uid']}&t=0&v=2.0&from=wxapp&c=entry&a=wxapp&do=api&core=core2&m=".$model_name."&s=/article/articleHtml/articleList";

            $article_url = 'https://' . $_SERVER['HTTP_HOST'] . "/app/index.php?i={$_GET['i']}&uid={$_GET['uid']}&t=0&v=2.0&from=wxapp&c=entry&a=wxapp&do=api&core=core2&m=".$model_name."&s=/article/articleHtml/html";

            $record_url = 'https://' . $_SERVER['HTTP_HOST'] . "/app/index.php?i={$_GET['i']}&uid={$_GET['uid']}&t=0&v=2.0&from=wxapp&c=entry&a=wxapp&do=api&core=core2&m=".$model_name."&s=/article/articleHtml/upRecordLength";

            $count_url = 'https://' . $_SERVER['HTTP_HOST'] . "/app/index.php?i={$_GET['i']}&uid={$_GET['uid']}&id={$count_id}&t=0&v=2.0&from=wxapp&c=entry&a=wxapp&do=api&core=core2&m=".$model_name."&s=/article/articleHtml/reportDuration";

            $share_record_url = 'https://' . $_SERVER['HTTP_HOST'] . "/app/index.php?i={$_GET['i']}&uid={$_GET['uid']}&t=0&v=2.0&from=wxapp&c=entry&a=wxapp&do=api&core=core2&m=".$model_name."&s=/article/articleHtml/shareRecord";
        } else {

            $list_url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . "?i={$_GET['i']}&uid={$_GET['uid']}&t=0&v=2.0&from=wxapp&c=entry&a=wxapp&do=api&core=core2&m=".$model_name."&s=/article/articleHtml/articleList";

            $article_url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] .  "?i={$_GET['i']}&uid={$_GET['uid']}&t=0&v=2.0&from=wxapp&c=entry&a=wxapp&do=api&core=core2&m=".$model_name."&s=/article/articleHtml/html";

            $record_url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . "?i={$_GET['i']}&uid={$_GET['uid']}&t=0&v=2.0&from=wxapp&c=entry&a=wxapp&do=api&core=core2&m=".$model_name."&s=/article/articleHtml/upRecordLength";

            $count_url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] .  "?i={$_GET['i']}&uid={$_GET['uid']}&id={$count_id}&t=0&v=2.0&from=wxapp&c=entry&a=wxapp&do=api&core=core2&m=".$model_name."&s=/article/articleHtml/reportDuration";

            $share_record_url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] .  "?i={$_GET['i']}&uid={$_GET['uid']}&t=0&v=2.0&from=wxapp&c=entry&a=wxapp&do=api&core=core2&m=".$model_name."&s=/article/articleHtml/shareRecord";
        }



        //  转义html内容
        $content = htmlspecialchars_decode($article['content']);
        $article['content'] = '';


        //  js-sdk
        $js_token = $this->getArticleAccessToken($config['gzh_appid'], $config['gzh_secret'], $article['uniacid']);
        $jsapi_ticket = $this->getArticleJsapiTicket($config['gzh_appid'], $config['gzh_secret'], $js_token, $article['uniacid']);
        if ($jsapi_ticket == 40001)
        {
            delCache('articleToken-', $article['uniacid']);
            delCache('articleJsapiTicket-', $article['uniacid']);
            $js_token = $this->getArticleAccessToken($config['gzh_appid'], $config['gzh_secret'], $article['uniacid']);
            $jsapi_ticket = $this->getArticleJsapiTicket($config['gzh_appid'], $config['gzh_secret'], $js_token, $article['uniacid']);
        }

        $timestamp = time();

        $nonceStr = uniqid() . rand(10000, 99999);


        $from_data = 'wxapp';

        if (isset($_GET['from']) && !empty($_GET['from'])) $from_data = $_GET['from'];

        if (defined('IS_WEIQIN')) {

            $url_now = $_W['siteroot'] . "app/index.php?i={$_GET['i']}&id={$_GET['id']}&uid={$_GET['uid']}&t=0&v=2.0&from={$from_data}&c=entry&a=wxapp&do=api&core=core2&m=".$model_name."&s=/article/articleHtml/html&code={$code}&state=STATE";
        } else {

            $from_data = '';

            $isappinstalled = '';

            if (isset($_GET['from']) && !empty($_GET['from'])) $from_data = '&from='.$_GET['from'];

            if (isset($_GET['isappinstalled'])) $isappinstalled = '&isappinstalled='.$_GET['isappinstalled'];

            $url_now = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] ."?s=/article/articleHtml/html&id={$_GET['id']}&uid={$_GET['uid']}&i={$_GET['i']}{$from_data}{$isappinstalled}&code={$code}&state=STATE";
        }

//        dump($url_now);exit;

        $str = "jsapi_ticket={$jsapi_ticket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url_now}";

        $signature = sha1($str);

        //转换标题
        $article['title'] = str_replace('"',"'",$article['title']);

        $article['title'] = str_replace('“',"'",$article['title']);

        $article['title'] = str_replace('”',"'",$article['title']);

        $article['title'] = str_replace('…',"...",$article['title']);

        $article['title'] = str_replace('——',"-",$article['title']);

        View::assign('signature', $signature);
        View::assign('nonceStr', $nonceStr);
        View::assign('timestamp', $timestamp);
        View::assign('url_now', $url_now);
        View::assign('str', $str);


        View::assign('article', $article);
        View::assign('config', $config);
        View::assign('content', $content);
        View::assign('userInfo', $userInfo);
        View::assign('company', $company);
        View::assign('job', $job);
        View::assign('articles', $articles);




        View::assign('qr_path', $qr_path);
        View::assign('to_uid', $article['user_id']);
        View::assign('list_url', $list_url);
        View::assign('article_url', $article_url);
        View::assign('record_id', $record_id);
        View::assign('record_url', $record_url);
        View::assign('count_url', $count_url);
        View::assign('share_record_url', $share_record_url);
        View::assign('count_id', $count_id);

//        View::assign('look_card', $config['']);

        // 模板输出
        return View::fetch();
    }


    public function articleList()
    {

        $model_name = config('app.AdminModelList')['app_model_name'];

        if (defined('IS_WEIQIN') ) {

            global $_W;
            $article_url = 'https://' . $_SERVER['HTTP_HOST'] . "/app/index.php?i={$_GET['uniacid']}&uid={$_GET['uid']}&t=0&v=2.0&from=wxapp&c=entry&a=wxapp&do=api&core=core2&m=".$model_name."&s=/article/articleHtml/html";
            $list_api = 'https://' . $_SERVER['HTTP_HOST'] . "/app/index.php?i={$_GET['uniacid']}&uid={$_GET['uid']}&t=0&v=2.0&from=wxapp&c=entry&a=wxapp&do=api&core=core2&m=".$model_name."&s=/article/articleHtml/myArticle";


        } else {

            $article_url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] .  "?i={$_GET['i']}&uid={$_GET['uid']}&t=0&v=2.0&from=wxapp&c=entry&a=wxapp&do=api&core=core2&m=".$model_name."&s=/article/articleHtml/html";
            $list_api = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] .  "?i={$_GET['i']}&uid={$_GET['uid']}&t=0&v=2.0&from=wxapp&c=entry&a=wxapp&do=api&core=core2&m=".$model_name."&s=/article/articleHtml/myArticle";

        }

        View::assign('to_uid', $_GET['uid']);
        View::assign('list_api', $list_api);
        View::assign('article_url', $article_url);
        // 模板输出
        return View::fetch();
    }

    /**
     * @Purpose: 我的文章列表
     *
     * @Param: int $classify_id     分类id
     * @Param: int $hot             是否是热门文章列表 1 => 是 0 => 否
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function myArticle()
    {


//        dump('aaa');exit;
        $uniacid = $this->request->param('i');
        $classify_id = $this->request->param('classify_id');
        $page = $this->request->param('page');
        $hot = $this->request->param('hot');
        $article_id = $this->request->param('article_id');
        $to_uid = $this->request->param('to_uid');

        $user_id = $this->request->param('user_id');

        $to_uid = $to_uid ? $to_uid : $user_id;

        global $_W;
        $_W['uid'] = $user_id;

        $page = intval($page);

        if (!$page)
        {
            $page = 0;
        }

        $articleModel = new ArticleModel();

        $where = [
            ['uniacid', '=', $uniacid],
            ['user_id', '=', $to_uid],
            ['status', '=', 1],
        ];

        if ($classify_id)
        {
            $where[] = ['classify_id', '=', $classify_id];
        }


        $field = 'id, title, cover, share, view, classify_id, create_time, poster, update_time';

        $limit = 20;
        $order = ['update_time' => 'desc', 'id' => 'desc'];
        if ($hot)
        {
            $limit = 5;
            $order = ['view' => 'desc', 'update_time' => 'desc', 'id' => 'desc'];
            $where[] = ['id', '<>', $article_id];
        }
        //  列表
        $list = $articleModel
            ->field($field)
            ->order($order)
            ->where($where)
            ->paginate($limit, false, ['page' => $page]);

        $list = json_encode($list);
        $list = json_decode($list, true);

        if ($list['data'])
        {
            $classifyModel = new ArticleClassifyModel();

            $classify = $classifyModel
                ->field('id, title')
                ->where(['uniacid' => $uniacid])
                ->select();

            foreach ($list['data'] as $index => $item) {
                $tmp_time = strtotime($item['update_time']);
                $list['data'][$index]['create_time2'] = lb_friendly_date($tmp_time);
                foreach ($classify as $k => $v) {
                    if ($item['classify_id'] == $v['id']) {
                        $list['data'][$index]['classify_title'] = $v['title'];
                    }
                }
            }
        }
        $recordModel = new ArticleRecordModel();
        $total_view = $recordModel->where(['staff_id' => $to_uid, 'type' => 1])->count();

        $date = date('Y-m-d');
        $time = strtotime($date . ' 00:00:00');
        $today_view = $recordModel
            ->where([
                'staff_id' => $to_uid,
                'type' => 1,
                'create_time' => ['>', $time]
            ])
            ->count();
        $list['total_view'] = $total_view;
        $list['today_view'] = $today_view;

        $whereList = array(
            'uniacid' => $uniacid,
            'type' => 1
        );

        $subQuery = Db::name('lb_marketing_record')
            ->where($whereList)
            ->group('user_id')
            ->buildSql();

        $rank = Db::table($subQuery . ' a')
            ->field(array(
                "count(a.user_id)" => "countUser",
                'b.nickName', 'b.avatarUrl', 'c.name', 'c.avatar'
            ))
            ->join('longbing_card_user b', 'b.id = a.staff_id', 'left')
            ->join('longbing_card_user_info c', 'c.fans_id = b.id', 'left')
            ->order(['countUser' => 'desc'])
            ->group('a.staff_id')
            ->limit(3)
            ->select();

        if (!empty($rank))
        {
            foreach ($rank as $index => $item) {
//                $rank[$index]['avatar'] = $this->lb_src_trans($item['avatar'], false, $_W);
            }
        }


        $list['rank'] = $rank;


        return $this->success($list);
    }


    public function upRecordLength()
    {
        $record_id = $this->request->param('record_id');


        $record = ArticleRecordModel::where('id', '=', $record_id)->find();
        if (!$record)
        {
            $msg = '没有找到记录';
            return $this->success($msg);
        }
        $record->length = $record->length + time() - $record->update_time;
        $record->save();
        return Json::create('ddd');

    }


    public function reportDuration ()
    {
        $id = $this->request->param('id');

        $radarCount = new RadarCount();

        $info = $radarCount->where( 'id', '=', $id )->find();
        if ( !$info )
        {
            $this->error( 'report fail', 400 );
        }

        $info->duration += time() - $info->update_time;
        $info->save();
        return $this->success( [] );
    }

    public function success($data, $code = 200)
    {
        $result['data'] = $data;
        $result['code'] = $code;
        $result['sign'] = null;
        //复杂的签名
        //		if(isset($this->_user['keys'])){
        //			$result['sign'] = rsa2CreateSign($this->_user['keys'] ,json_encode($data));
        //		}
        //简单的签名
        if (!empty($this->_token)) $result['sign'] = createSimpleSign($this->_token, is_string($data) ? $data : json_encode($data));
        return $this->response($result, 'json', $code);
    }

    protected function response($data, $type = 'json', $code = 200)
    {
        return Response::create($data, $type)->code($code);
    }

    private function setClients($to_uid, $user_id, $article_id, $record_id, $uniacid)
    {
        $recordModel = new ArticleRecordModel();
        $tmp = date('Y-m-d') . ' 00:00:00';
        $times = strtotime($tmp);
        $count = $recordModel
            ->where([
                ['article_id', '=', $article_id],
                ['user_id', '=', $user_id],
                ['staff_id', '=', $to_uid],
                ['type', '=', 1],
                ['uniacid', '=', $uniacid],
                ['id', '<', $record_id],
                ['create_time', '>', $times]
            ])
            ->count();

        if ($count)
        {
            return false;
        }

        $date = date('m/d');
        $year = date('Y');
        $info = ArticleDateModel::where([
            'user_id' => $to_uid,
            'uniacid' => $uniacid,
            'month_day' => $date,
            'year' => $year,
        ])
            ->find();

        if ($info)
        {
            $info->count += 1;
            $info->save();
        } else {
            ArticleDateModel::create([
                'user_id' => $to_uid,
                'uniacid' => $uniacid,
                'month_day' => $date,
                'year' => $year,
                'count' => 1,
            ]);
        }
        return true;
    }

    private function lb_src_trans($src, $local_path = false, $_W)
    {

        if (empty($src))
        {
            return '';
        }
        if (strexists($src, "c=utility&a=wxcode&do=image&attach="))
        {
            return $src;
        }
        if (strexists($src, 'addons/'))
        {
            return $_W['siteroot'] . substr($src, strpos($src, 'addons/'));
        }
        if (strexists($src, $_W['siteroot']) && !strexists($src, '/addons/'))
        {
            $urls = parse_url($src);
            $src = $t = substr($urls['path'], strpos($urls['path'], 'images'));
        }
        $t = strtolower($src);
        if (strexists($t, 'https://mmbiz.qlogo.cn') || strexists($t, 'http://mmbiz.qpic.cn'))
        {
            $url = url('utility/wxcode/image', array('attach' => $src));
            return $_W['siteroot'] . 'web' . ltrim($url, '.');
        }
        if ((substr($t, 0, 7) == 'http://') || (substr($t, 0, 8) == 'https://') || (substr($t, 0, 2) == '//'))
        {
            return $src;
        }
        if ($local_path || empty($_W['setting']['remote']['type']) || file_exists(IA_ROOT . '/' . $_W['config']['upload']['attachdir'] . '/' . $src))
        {
            $src = $_W['siteroot'] . $_W['config']['upload']['attachdir'] . '/' . $src;
        } else {
            $src = $_W['attachurl_remote'] . $src;
        }
        return $src;
    }


    public function getArticleAccessToken($appid, $gzh_secret, $uniacid)
    {
        $key = 'articleToken-';
        $value = getCache($key, $uniacid);
        if ($value)
        {
            return $value;
        }

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$gzh_secret}";

        $js_token = file_get_contents($url);
        $js_token = json_decode($js_token, true);


        if (isset($js_token['access_token']))
        {
            $js_token = $js_token['access_token'];
            setCache($key, $js_token, 7000, $uniacid);
            return $js_token;
        }


        $str = '请求ac错误' . isset($js_token['errmsg']) ? $js_token['errmsg'] : '';
        echo $str;
        die;
    }

    public function getArticleJsapiTicket($appid, $gzh_secret, $js_token, $uniacid)
    {
        $key = 'articleJsapiTicket-';
        $value = getCache($key, $uniacid);
        if ($value)
        {
            return $value;
        }

        $ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$js_token}&type=jsapi";

        $ticket_arr = file_get_contents($ticket_url);
        $ticket_arr = json_decode($ticket_arr, true);


        if (isset($ticket_arr['errcode']) && $ticket_arr['errcode'] != 0)
        {
            if ($ticket_arr['errcode'] == 40001)
            {
                return 40001;
            }
            echo $ticket_arr['errmsg'];
            die;
        }
        $jsapi_ticket = $ticket_arr['ticket'];

        return $jsapi_ticket;
    }


    public function shareRecord()
    {
        $uniacid = $this->request->param('i');
        $id = $this->request->param('id') ?? null;
        $to_uid = $this->request->param('to_uid') ?? null;
        $type_get = $this->request->param('type') ?? 1;
        $record_id = $this->request->param('record_id') ?? null;


        if ($record_id)
        {
            $record = ArticleRecordModel::where('id', '=', $record_id);
            if (!$record) {
                $msg = '没有找到记录';
                return $this->error($msg);
            }
            $record->length  = $record->length + time() - $record->update_time;
            $record->save();
            return $this->success('suc');
        }

        $user_id = $this->_user_id ?? $this->request->param('uid') ?? null;

        if (!$id || !$user_id)
        {
            return $this->error('param is required');
        }

        $userModel = new User();
        $user = $userModel->where(['id' => $user_id])->find();

        if (!$user)
        {
            return $this->error('this record not found');
        }

        $articleModel = new ArticleModel();

        $article = $articleModel
            ->where(['id' => $id, 'status' => 1])
            ->find();

        if (!$article)
        {
            return $this->error('this record not found');
        }

        //  判断是否做记录
        if ($user_id != $article['user_id'] && $article['user_id'] != 0)
        {

            $recordModel = new ArticleRecordModel();
            $type = 2;

            if ($type_get == 2)
            {
                $type = 5; //分享海报
                $article->poster = $article->poster + 1;
                $article->save();
            } else {
                $article->share = $article->share + 1;
                $article->share_other += 1;
                $article->save();
            }
            $count = $recordModel
                ->where([
                    'article_id' => $id,
                    'user_id' => $user_id,
                    'staff_id' => $to_uid,
                    'type' => $type,
                    'uniacid' => $uniacid,
                ])
                ->count();

            $recordModel->article_id = $id;
            $recordModel->user_id = $user_id;
            $recordModel->staff_id = $to_uid;
            $recordModel->type = $type;
            $recordModel->number = $count + 1;

            $recordModel->uniacid = $uniacid;
            $recordModel->save();


            $countModel = new CardCount();
            $countModel->user_id = $user_id;
            $countModel->to_uid = $to_uid;
            $countModel->sign = 'view';
            $countModel->type = 13;
            if ($type_get == 2) {
                $countModel->type = 14; //分享海报
            }
            $countModel->uniacid = $uniacid;
            $countModel->target = $id;
            $countModel->save();


            //发送雷达通知
            if (!empty($countModel->id)) {
                $push_data = array(
                    'action' => 'SendWxServiceNotice',
                    'event' => 'SendWxServiceNotice',
                    'count_id' => $countModel->id
                );
                publisher(json_encode($push_data, true), 5000);
            }

        } else {
            $article->share_self += 1;
            $article->save();
        }

        return $this->success('suc');

    }

}